package lol.clann.minecraft.springboot.plugin.hook;

import com.ruoshui.utils.java.exception.ExceptionUtils;
import lol.clann.minecraft.springboot.api.context.PluginContext;
import lol.clann.minecraft.springboot.api.context.SpringContext;
import lol.clann.minecraft.springboot.api.model.core.Plugin;
import lol.clann.minecraft.springboot.api.utils.ConfigUtils;
import lombok.extern.slf4j.Slf4j;
import okio.Okio;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 进行配置注入
 *
 * @author pyz
 * @date 2019/5/2 3:04 PM
 */
@Slf4j
@Component
public class ConfigProcessor implements InstantiationAwareBeanPostProcessor, ApplicationRunner {
    /**
     * 在postInstance之前,注入配置
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        try {
            ConfigUtils.resolve(bean);
        } catch (Throwable e) {
            ExceptionUtils.throwException(e);
        }
        return bean;
    }

    /**
     * 启动完毕,保存配置文件
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        for (Plugin plugin : PluginContext.getPlugins()) {
            plugin.saveConfig();
        }

        String debugConfig = SpringContext.getApplicationEnvironment().getProperty("springbootplugin.debug.config", "false");
        if (Boolean.valueOf(debugConfig)) {
            LOGGER.warn("配置文件调试模式处于开始状态,将打印所有SBP插件配置文件内容...");
            for (Plugin plugin : PluginContext.getPlugins()) {
                LOGGER.warn(plugin.getDisplayName() + ": " + plugin.getConfig().toAbsolutePath().toString());
                try {
                    String content = Okio.buffer(Okio.source(plugin.getConfig().toFile())).readUtf8();
                    LOGGER.info(content);
                } catch (IOException e) {
                    ExceptionUtils.throwException(e);
                }
            }
        }
    }
}
